package com.bigstar.lolen_e;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.AlertDialog;
import android.app.ExpandableListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class Rune extends ExpandableListActivity {
	
	public static int red[] = {-1,-1,-1,-1,-1,-1,-1,-1,-1};
	public static int blue[] = {-1,-1,-1,-1,-1,-1,-1,-1,-1};
	public static int yellow[] = {-1,-1,-1,-1,-1,-1,-1,-1,-1};
	public static int big[] = {-1,-1,-1};
	
	private RunExpandableAdapter adapter;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        ChampionData.load(this);
        ItemData.load(this);
        Rune.load(this);
		setContentView(R.layout.rune_list);
		
        adapter = new RunExpandableAdapter(this);
    	setListAdapter(adapter);
		Button tv = (Button)findViewById(R.id.rune_effect_text);
		tv.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				String stat = setEffect();
				if(!stat.equals("")){
					AlertDialog.Builder alt_bld = new AlertDialog.Builder(Rune.this);  
					alt_bld.setMessage(stat).setCancelable(false)
							.setNegativeButton("Close",  
				    		   new DialogInterface.OnClickListener() {  
								public void onClick(DialogInterface dialog, int id) {  
									// Action for 'NO' Button  
									dialog.cancel();  
								}  
							});  
					AlertDialog alert = alt_bld.create();  
					alert.setTitle("Rune Stat Info");   
					alert.show(); 	
				}else{
					Toast.makeText(Rune.this, "Rune select.", Toast.LENGTH_SHORT).show();
				}
			}
			
		});
    }
	
	public String setEffect(){
		String text = "";
		float mana_regen = getStat("mana_regen");
		if(mana_regen != 0.00f){	text += "+"+String.format("%.2f", mana_regen)+" Mana regen / 5 sec.\r\n";	}
		float mana_regen_per_lvl = getStat("mana_regen_per_lvl");
		if(mana_regen_per_lvl != 0.00f){	text += "+"+String.format("%.2f", mana_regen_per_lvl)+" mana regen / 5 sec. per level ("+String.format("%.2f", mana_regen_per_lvl*18)+" at Champion level 18)\r\n";	}
		float health_regen = getStat("health_regen");
		if(health_regen != 0.00f){	text += "+"+String.format("%.2f", health_regen)+" Health regen / 5 sec.\r\n";	}
		float health_regen_per_lvl = getStat("health_regen_per_lvl");
		if(health_regen_per_lvl != 0.00f){	text += "+"+String.format("%.2f", health_regen_per_lvl)+" health regen / 5 sec. per level ("+String.format("%.2f", health_regen_per_lvl*18)+" at Champion level 18)\r\n";	}
		float mana_per_lvl = getStat("mana_per_lvl");
		if(mana_per_lvl != 0.00f){	text += "+"+String.format("%.2f", mana_per_lvl)+"Mana per level ("+String.format("%.2f", mana_per_lvl*18)+" at Champion level 18)\r\n";	}
		float mana = getStat("mana");
		if(mana != 0.00f){	text += "+"+String.format("%.2f", mana)+" Mana\r\n";	}
		float ap_per_lvl = getStat("ap_per_lvl");
		if(ap_per_lvl != 0.00f){	text += "+"+String.format("%.2f", ap_per_lvl)+"Ability power per level ("+String.format("%.2f", ap_per_lvl*18)+" at Champion level 18)\r\n";	}
		float magic_pen = getStat("magic_pen");
		if(magic_pen != 0.00f){	text += "+"+String.format("%.2f", magic_pen)+" Magic penetration\r\n";	}
		float ap = getStat("ap");
		if(ap != 0.00f){	text += "+"+String.format("%.2f", ap)+" Ability power\r\n";	}
		float cooldowns = getStat("cooldowns");
		if(cooldowns != 0.00f){	text += "-"+String.format("%.2f", cooldowns)+"% Cooldowns\r\n";	}
		float cri_chance = getStat("cri_chance");
		if(cri_chance != 0.00f){	text += "+"+String.format("%.2f", cri_chance)+"% Critical chance\r\n";	}
		float cri_damage = getStat("cri_damage");
		if(cri_damage != 0.00f){	text += "+"+String.format("%.2f", cri_damage)+" critical damage\r\n";	}
		float attack_speed = getStat("attack_speed");
		if(attack_speed != 0.00f){	text += "+"+String.format("%.2f", attack_speed)+"% attack speed\r\n";	}
		float damage_per_lvl = getStat("damage_per_lvl");
		if(damage_per_lvl != 0.00f){	text += "+"+String.format("%.2f", damage_per_lvl)+" attack damage per level (+"+String.format("%.2f", damage_per_lvl*18)+" at champion level 18)\r\n";	}
		float armor_pen = getStat("armor_pen");
		if(armor_pen != 0.00f){	text += "+"+String.format("%.2f", armor_pen)+" armor penetration\r\n";	}
		float health = getStat("health");
		if(health != 0.00f){	text += "+"+String.format("%.2f", health)+" health\r\n";	}
		float mr_per_lvl = getStat("mr_per_lvl");
		if(mr_per_lvl != 0.00f){	text += "+"+String.format("%.2f", mr_per_lvl)+" magic resist per level (+"+String.format("%.2f", mr_per_lvl*18)+" at champion level 18)\r\n";	}
		float mr = getStat("mr");
		if(mr != 0.00f){	text += "+"+String.format("%.2f", mr)+" magic resist\r\n";	}
		float armor = getStat("armor");
		if(armor != 0.00f){	text += "+"+String.format("%.2f", armor)+" armor\r\n";	}
		float health_per_lvl = getStat("health_per_lvl");
		if(health_per_lvl != 0.00f){	text += "+"+String.format("%.2f", health_per_lvl)+" health per level (+"+String.format("%.2f", health_per_lvl*18)+" at champion level 18)\r\n";	}
		float damage = getStat("damage");
		if(damage != 0.00f){	text += "+"+String.format("%.2f", damage)+" attack damage\r\n";	}
		float energy_per_lvl = getStat("energy_per_lvl");
		if(energy_per_lvl != 0.00f){	text += "+"+String.format("%.2f", energy_per_lvl)+" Energy per level (+"+String.format("%.2f", energy_per_lvl*18)+" at level 18)\r\n";	}
		float energy = getStat("energy");
		if(energy != 0.00f){	text += "+"+String.format("%.2f", energy)+" Energy\r\n";	}
		float energy_regen_per_level = getStat("energy_regen_per_lvl");
		if(energy_regen_per_level != 0.00f){	text += "+"+String.format("%.2f", energy_regen_per_level)+"Energy per level ("+String.format("%.2f", energy_regen_per_level*18)+" at Champion level 18)\r\n";	}
		float cooldowns_per_lvl = getStat("cooldowns_per_lvl");
		if(cooldowns_per_lvl != 0.00f){	text += "-"+String.format("%.2f", cooldowns_per_lvl)+"% cooldowns per level (-"+String.format("%.2f", cooldowns_per_lvl*18)+"% at champion level 18)\r\n";	}
		float armor_per_lvl = getStat("armor_per_lvl");
		if(armor_per_lvl != 0.00f){	text += "+"+String.format("%.2f", armor_per_lvl)+" armor per level (+"+String.format("%.2f", armor_per_lvl*18)+" at champion level 18)\r\n";	}
		float move_speed = getStat("move_speed");
		if(move_speed != 0.00f){	text += "+"+String.format("%.2f", move_speed)+"% movement speed\r\n";	}
		float hsec_gold = getStat("hsec_gold");
		if(hsec_gold != 0.00f){	text += "+"+String.format("%.2f", hsec_gold)+" gold / 10 sec.\r\n";	}
		float spell_vamp = getStat("spell_vamp");
		if(spell_vamp != 0.00f){	text += "+"+String.format("%.2f", spell_vamp)+"% Spellvamp\r\n";	}
		float life_steal = getStat("life_steal");
		if(life_steal != 0.00f){	text += "+"+String.format("%.2f", life_steal)+"% life steal\r\n";	}
		float health_per = getStat("health_per");
		if(health_per != 0.00f){	text += "+"+String.format("%.2f", health_per)+"% health";	}
		return text;
	}
	
	public static float getStat(String name){
		float health = 0;
		for(int i = 0; i < red.length; i++){
			if(red[i] != -1){
				if(runes.get(red[i]).stat_name != null && runes.get(red[i]).stat_name.equalsIgnoreCase(name)){
					health += runes.get(red[i]).stat;
				}	
			}
		}
		for(int i = 0; i < blue.length; i++){
			if(blue[i] != -1){
				if(runes.get(blue[i]).stat_name != null && runes.get(blue[i]).stat_name.equalsIgnoreCase(name)){
					health += runes.get(blue[i]).stat;
				}	
			}
		}
		for(int i = 0; i < yellow.length; i++){
			if(yellow[i] != -1){
				if(runes.get(yellow[i]).stat_name != null && runes.get(yellow[i]).stat_name.equalsIgnoreCase(name)){
					health += runes.get(yellow[i]).stat;
				}	
			}
		}
		for(int i = 0; i < big.length; i++){
			if(big[i] != -1){
				if(runes.get(big[i]).stat_name != null && runes.get(big[i]).stat_name.equalsIgnoreCase(name)){
					health += runes.get(big[i]).stat;
				}	
			}
		}
		return health;
	}
    
    
    public static ArrayList<RuneTemplate> runes = new ArrayList<RuneTemplate>();
	
	public static void load(Context context){
		String data = null;
		if(runes.size() <= 0){
			try {
				data = Utils.getXMLFileFromAssets(context, "runes.xml");
				PullParserFromXML(data);
			} catch (IOException e) {
			}	
		}
	}
	
	public static void PullParserFromXML(String data) {
		try {
			XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
			factory.setNamespaceAware(true);
			XmlPullParser xpp = factory.newPullParser();

			xpp.setInput(new StringReader(data));
			int eventType = xpp.getEventType();
			RuneTemplate rune = null;
			while (eventType != XmlPullParser.END_DOCUMENT) {
				if(eventType == XmlPullParser.START_TAG){
					if(xpp.getName().equals("rune")){
						rune = new RuneTemplate();
					}else if(xpp.getName().equals("name_kor")){
						//rune.name = xpp.nextText();
					}else if(xpp.getName().equals("name")){
						rune.name = xpp.nextText();
					}else if(xpp.getName().equals("image_name")){
						rune.image_name = xpp.nextText();
					}else if(xpp.getName().equals("text")){
						//rune.text = xpp.nextText();
					}else if(xpp.getName().equals("text_en")){
						rune.text = xpp.nextText();
					}else if(xpp.getName().equals("price")){
						rune.price = Integer.parseInt(xpp.nextText());
					}else{
						if(!xpp.getName().equals("runes")){
							rune.stat_name = xpp.getName();
							rune.stat = Float.parseFloat(xpp.nextText());
						}
					}
				}else if(eventType == XmlPullParser.END_TAG){
					if(xpp.getName().equals("rune")){
						runes.add(rune);
					}
				}
				eventType = xpp.next();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	@Override
    protected void onResume() {
        ChampionData.load(this);
        ItemData.load(this);
        Rune.load(this);
    	super.onResume();
        if(adapter != null){
        	adapter.notifyDataSetChanged();
        }
		totalUpdate();
    }
	
	public void totalUpdate(){
		int total = 0;
		for(int i = 0; i < Rune.red.length; i++){
			if(Rune.red[i] != -1){
				total += runes.get(red[i]).price;
			}
		}
		for(int i = 0; i < Rune.blue.length; i++){
			if(Rune.blue[i] != -1){
				total += runes.get(blue[i]).price;
			}
		}
		for(int i = 0; i < Rune.yellow.length; i++){
			if(Rune.yellow[i] != -1){
				total += runes.get(yellow[i]).price;
			}
		}
		for(int i = 0; i < Rune.big.length; i++){
			if(Rune.big[i] != -1){
				total += runes.get(big[i]).price;
			}
		}
		TextView tv = (TextView)findViewById(R.id.rune_total);
		tv.setText("Total : "+total+" IP");
	}
	
    public class RunExpandableAdapter extends BaseExpandableListAdapter {

    	private Context context;
    	
    	private String[] group = {"Mark","Glyph","Seal","Quintessence"};
    	
		public RunExpandableAdapter(Context context) {
			this.context = context;
		}
		@Override
        public Object getChild(int groupPosition, int childPosition) {
			if(groupPosition == 0){
				return red[childPosition];
			}else if(groupPosition == 1){
				return blue[childPosition];
			}else if(groupPosition == 2){
				return yellow[childPosition];
			}else if(groupPosition == 3){
				return big[childPosition];
			}
            return null;
        }

		@Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }
		int delete_rune_num = 0;
		int delete_group = 0;
		int delete_child = 0;
		public void deleteRune(int groupPosition, int childPosition){
			AlertDialog.Builder alt_bld = new AlertDialog.Builder(Rune.this);  
			delete_rune_num = (Integer)getChild(groupPosition, childPosition);
	        String path = "rune_img/"+runes.get(delete_rune_num).image_name+".png";
			delete_group = groupPosition;
			delete_child = childPosition; 
			alt_bld.setMessage(runes.get(delete_rune_num).name+"\r\n"+runes.get(delete_rune_num).text).setCancelable(  
					false).setPositiveButton("Yes",  
							new DialogInterface.OnClickListener() {  
						public void onClick(DialogInterface dialog, int id) {  
							if(delete_group == 0){
								red[delete_child] = -1;
							}else if(delete_group == 1){
								blue[delete_child] = -1;
							}else if(delete_group == 2){
								yellow[delete_child] = -1;
							}else if(delete_group == 3){
								big[delete_child] = -1;
							}
							adapter.notifyDataSetChanged();
							totalUpdate();
						}  
					}).setNegativeButton("No",  
		    		   new DialogInterface.OnClickListener() {  
						public void onClick(DialogInterface dialog, int id) {  
							// Action for 'NO' Button  
							dialog.cancel();  
						}  
					});  
			AlertDialog alert = alt_bld.create();  
			alert.setTitle("Do you want to delete?");  
			try {
				alert.setIcon(Drawable.createFromStream(getAssets().open(path),"src"));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}  
			alert.show();
		}

		@Override
        public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
			convertView = View.inflate(context, R.layout.item_info_row, null); 
			ImageView icon = (ImageView)convertView.findViewById(R.id.item_img);
			TextView item_name = (TextView)convertView.findViewById(R.id.item_name); 
			TextView item_text = (TextView)convertView.findViewById(R.id.item_text); 
			if(groupPosition == 0){
				if(red[childPosition] == -1){
					icon.setImageResource(R.drawable.rune_red);
					item_name.setText("Please select rune");	
				}else{
			        String path = "rune_img/"+runes.get(red[childPosition]).image_name+".png";
					try {
						icon.setImageDrawable(Drawable.createFromStream(getAssets().open(path),"src"));
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					item_name.setText(runes.get(red[childPosition]).name+"("+runes.get(red[childPosition]).price+"IP)");
					item_text.setText(runes.get(red[childPosition]).text);
				}
				convertView.setTag(childPosition);
	            convertView.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						int childPosition = Integer.valueOf(v.getTag().toString());
						if(red[childPosition] == -1){
							Intent intent = new Intent(Rune.this, RuneList.class);
							intent.putExtra("type", ""+(childPosition+1));
							startActivity(intent);
						}else{
							deleteRune(0, childPosition);
						}
					}
				}); 
			}else if(groupPosition == 1){
				if(blue[childPosition] == -1){
					icon.setImageResource(R.drawable.rune_blue);
					item_name.setText("Please select rune");	
				}else{
			        String path = "rune_img/"+runes.get(blue[childPosition]).image_name+".png";
					try {
						icon.setImageDrawable(Drawable.createFromStream(getAssets().open(path),"src"));
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					item_name.setText(runes.get(blue[childPosition]).name+"("+runes.get(blue[childPosition]).price+"IP)");
					item_text.setText(runes.get(blue[childPosition]).text);
				}
				convertView.setTag(childPosition);
	            convertView.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						int childPosition = Integer.valueOf(v.getTag().toString());
						if(blue[childPosition] == -1){
							Intent intent = new Intent(Rune.this, RuneList.class);
							intent.putExtra("type", ""+(10+childPosition+1));
							startActivity(intent);
						}else{
							deleteRune(1, childPosition);
						}
					}
				}); 
			}else if(groupPosition == 2){
				if(yellow[childPosition] == -1){
					icon.setImageResource(R.drawable.rune_yellow);
					item_name.setText("Please select rune");	
				}else{
			        String path = "rune_img/"+runes.get(yellow[childPosition]).image_name+".png";
					try {
						icon.setImageDrawable(Drawable.createFromStream(getAssets().open(path),"src"));
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					item_name.setText(runes.get(yellow[childPosition]).name+"("+runes.get(yellow[childPosition]).price+"IP)");
					item_text.setText(runes.get(yellow[childPosition]).text);
				}
				convertView.setTag(childPosition);
	            convertView.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						int childPosition = Integer.valueOf(v.getTag().toString());
						if(yellow[childPosition] == -1){
							Intent intent = new Intent(Rune.this, RuneList.class);
							intent.putExtra("type", ""+(20+childPosition+1));
							startActivity(intent);
						}else{
							deleteRune(2, childPosition);
						}
					}
				}); 
			}else if(groupPosition == 3){
				if(big[childPosition] == -1){
					icon.setImageResource(R.drawable.rune_violet);
					item_name.setText("Please select rune");	
				}else{
			        String path = "rune_img/"+runes.get(big[childPosition]).image_name+".png";
					try {
						icon.setImageDrawable(Drawable.createFromStream(getAssets().open(path),"src"));
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					item_name.setText(runes.get(big[childPosition]).name+"("+runes.get(big[childPosition]).price+"IP)");
					item_text.setText(runes.get(big[childPosition]).text);
				}
				convertView.setTag(childPosition);
	            convertView.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						int childPosition = Integer.valueOf(v.getTag().toString());
						if(big[childPosition] == -1){
							Intent intent = new Intent(Rune.this, RuneList.class);
							intent.putExtra("type", ""+(30+childPosition+1));
							startActivity(intent);
						}else{
							deleteRune(3, childPosition);
						}
					}
				}); 
			}
            return convertView;
		}

		@Override
        public int getChildrenCount(int groupPosition) {
			if(groupPosition == 0){
				return red.length;
			}else if(groupPosition == 1){
				return blue.length;
			}else if(groupPosition == 2){
				return yellow.length;
			}else if(groupPosition == 3){
				return big.length;
			}
			return 0;
		}

		@Override
        public Object getGroup(int groupPosition) {
            return group[groupPosition];
        }

		@Override
		public int getGroupCount() {
			return group.length;
		}

		@Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

		@Override
        public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
            convertView = View.inflate(context, R.layout.rune_row, null);
            TextView tvGroupTitle = (TextView) convertView.findViewById(R.id.rune_name);
            Button reset = (Button) convertView.findViewById(R.id.rune_reset);
            tvGroupTitle.setText(group[groupPosition]);
			if(groupPosition == 0){
				tvGroupTitle.setTextColor(0xffe22b2b);
				tvGroupTitle.setTextSize(15);
				tvGroupTitle.setText("<Mark>");
				reset.setText("Mark Init");
				reset.setOnClickListener(new OnClickListener(){
					@Override
					public void onClick(View v) {
						for(int i = 0; i < Rune.red.length; i++){
							Rune.red[i] = -1;
						}
						adapter.notifyDataSetChanged();
						totalUpdate();
					}
				});
			}else if(groupPosition == 1){
				tvGroupTitle.setTextColor(0xff2d54fc);
				tvGroupTitle.setTextSize(15);
				tvGroupTitle.setText("<Glyph>");	
				reset.setText("Glyph Init");
				reset.setOnClickListener(new OnClickListener(){
					@Override
					public void onClick(View v) {
						for(int i = 0; i < Rune.blue.length; i++){
							Rune.blue[i] = -1;
						}
						adapter.notifyDataSetChanged();
						totalUpdate();
					}
				});
			}else if(groupPosition == 2){
				tvGroupTitle.setTextColor(0xffffdb16);
				tvGroupTitle.setTextSize(15);
				tvGroupTitle.setText("<Seal>");	
				reset.setText("Seal Init");
				reset.setOnClickListener(new OnClickListener(){
					@Override
					public void onClick(View v) {
						for(int i = 0; i < Rune.yellow.length; i++){
							Rune.yellow[i] = -1;
						}
						adapter.notifyDataSetChanged();
						totalUpdate();
					}
				});
			}else if(groupPosition == 3){
				tvGroupTitle.setTextColor(0xffa553ea);
				tvGroupTitle.setTextSize(15);
				tvGroupTitle.setText("<Quintessence>");
				reset.setText("Quintessence Init");
				reset.setOnClickListener(new OnClickListener(){
					@Override
					public void onClick(View v) {
						for(int i = 0; i < Rune.big.length; i++){
							Rune.big[i] = -1;
						}
						adapter.notifyDataSetChanged();
						totalUpdate();
					}
				});
			}
			convertView.setTag(groupPosition);
            convertView.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					int groupPosition = Integer.valueOf(v.getTag().toString());
					if (Rune.this.getExpandableListView().isGroupExpanded(groupPosition)) {
						Rune.this.getExpandableListView().collapseGroup(groupPosition);
					} else {
						Rune.this.getExpandableListView().expandGroup(groupPosition);
					}
				}
			});  
            return convertView;
		}

		@Override
		public boolean hasStableIds() {
			// TODO Auto-generated method stub
			return true;
		}

		@Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
			// TODO Auto-generated method stub
			return true;
		}
    	
    }
}
